#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project : gtmsAutoTestProject 
@File    : overseas_upload_order_payload_server.py
@IDE     : PyCharm 
@Author  : Mario
@Date    : 2022/9/26 11:55 
@Describe: 海外订单数据组装接口业务实现
"""
from Comm.tools.toolsControl import ToolsHandler
from APIs.posApi.order.order_api import OrderApi
from Comm.sqlUtils.sqliteControl import SqliteHelper


def order_food_info_cleaning(food_info: list, order_no: str) -> list:
    """
    订单菜品数据清洗
    :param food_info: 菜品数据
    :param order_no: 订单编码
    :return:
    """
    food_list = []  # 订单菜品数据空列表
    # 循环传入的菜品列表
    for i in range(len(food_info)):
        # 组装菜品数据列表
        food_info_dict = {
            "orderFoodSerialNo": food_info[i]['orderFoodId'],  # 订单菜品流水号
            "saleNo": order_no,  # 订单编号
            "foodCode": food_info[i]['foodCode'],  # 菜品编码
            "foodName": food_info[i]['foodName'],  # 菜品名称
            "foodNum": food_info[i]['foodNum'],  # 菜品数量
            "foodUnitPrice": food_info[i]['realFoodUnitPrice'],  # 菜品单价
            "foodPrice": food_info[i]['totalAmount'],  # 菜品金额(合计金额)
            "discount": food_info[i]['discount'],  # 优惠金额
            "amount": food_info[i]['totalAmount'],  # 实收金额
            "orderTime": food_info[i]['createdAt']  # 下单时间
        }
        # 将菜品数据插入订单菜品数据空列表
        food_list.append(food_info_dict)
    return food_list


class OverseasUploadOrderPayloadServer:
    def __init__(self, brandCode, environment):
        self.sql_server = SqliteHelper('support.db')  # 实例化sqlite
        self.order_api = OrderApi(brandCode, environment)
        self.start_time = ToolsHandler.get_moon_start_time()  # 获取本月初时间
        self.now_time = ToolsHandler.get_now_time()  # 获取当前时间
        self.shop_code = ToolsHandler.get_shopCode(brandCode)  # 根据品牌编码获取测试店编码
        self.brand_code = brandCode
        self.environment = environment

    def get_order_list_order_no(self) -> [list, list]:
        """
        获取本月订单的订单编号(含逆向，不含外卖)
        :return:
        """
        # 获取当月订单列表
        order_list = self.order_api.order_summary_list(self.start_time, self.now_time)
        # 获取所有的订单号
        order_no = ToolsHandler.get_json_result(order_list, '$..orderNo')
        # 获取所有的会员id
        customer_id = ToolsHandler.get_json_result(order_list, '$..customerId')
        return order_no, customer_id

    def insert_sql_assembly(self, order_no, refund_order, payload, created_by="system"):
        """
        插入数据
        :param order_no: 订单编号
        :param refund_order: 是否为逆向单(0-正向单,1-逆向单)
        :param payload: 请求数据
        :param created_by: 创建人
        :return:
        """
        # 组装插入语句
        insert_sql = """INSERT INTO overseas_upload_order (brand_code,shop_code,environment,order_no,refund_order,payload,created_by)VALUES('{}','{}','{}','{}','{}',"{}",'{}');""".format(
            self.brand_code, self.shop_code, self.environment, order_no, refund_order, payload, created_by)
        # 执行插入操作
        self.sql_server.db_data_operate(insert_sql)

    def order_pay_info_cleaning(self, pay_info: list, order_no: str) -> list:
        """
        订单支付信息数据清洗
        :param pay_info: 支付信息
        :param order_no: 订单编码
        :return:
        """
        # 支付信息空列表
        pay_ment_list = []
        # 循环传入的支付列表
        for i in range(len(pay_info)):
            if pay_info[0]['payName'] == '现金支付':
                paymentWay = '01'
            else:
                paymentWay = '03'
            pay_ment_dict = {
                "brandCode": self.brand_code,
                "serialNo": pay_info[0]['serialNo'],  # 支付流水号
                "shopCode": self.shop_code,
                "shopName": "探鱼测试店",
                "saleNo": order_no,
                "payTime": pay_info[0]['payTime'],
                "paymentMethod": pay_info[0]['payCode'],  # 支付方式编号
                # 支付类型id：01 现金：当地币种、02银行卡：所有银行卡方式、03 线上支付：如applepay等其他当地流行的线上支付工具、04其他：预留
                "paymentWay": paymentWay,
                "totalAmount": pay_info[0]['payAmount'],  # 结算金额
                "amount": pay_info[0]['realAmount']  # 实收金额
            }
            # 插入支付信息空列表
            pay_ment_list.append(pay_ment_dict)
        return pay_ment_list

    def order_upload_data_cleaning(self, detail_data, pay_info: list, food_info: list, saleReturn='0') -> dict:
        """
        物业上传数据组装
        :param detail_data: 订单信息
        :param pay_info: 支付信息
        :param food_info: 菜品信息
        :param saleReturn: 是否退货单
        :return:
        """
        upload_data_dict = {
            "brandCode": self.brand_code,
            "shopCode": self.shop_code,
            "saleNo": detail_data['orderInfo']['orderNo'],
            "posNo": "posNo",  # 收款机编号
            "cashier": detail_data['orderInfo']['operatorName'],  # 收款人编号
            "foodNum": len(food_info),
            "saleAmount": detail_data['orderInfo']['totalAmount'],  # 订单金额
            "cashIncomeAmount": detail_data['orderInfo']['actualPay'],  # 实收金额
            "payDiscount": detail_data['orderInfo']['discountMoney'],  # 优惠金额
            "orderTime": detail_data['orderInfo']['orderStartTime'],  # 下单时间:yyyy-mm-dd hh:mm:ss
            "finishTime": detail_data['orderInfo']['orderStartTime'],  # 结算时间:yyyy-mm-dd hh:mm:ss
            "uploadTime": self.now_time,  # 上传时间
            "saleReturn": saleReturn,  # 是否退货单：0-正向单，1-退货单
            "foodList": food_info,  # 菜品信息[list]
            "paymentList": pay_info  # 支付信息[list]
        }
        return upload_data_dict

    def order_data_cleaning(self):
        """
        订单数据清洗并存入数据库
        :return:
        """
        order_no_list = self.get_order_list_order_no()[0]  # 获取当月所有订单号
        customer_id_list = self.get_order_list_order_no()[1]  # 获取所有订单号的会员id
        # 循环所有的订单号
        for i in range(len(order_no_list)):
            # 如果订单号的开头为1说明是正向单
            if order_no_list[i][0] == '1':
                # 调用堂食正向订单详情接口获取订单详情
                order_detail = self.order_api.order_summary_canteen_detail(orderNo=order_no_list[i], customerId=str(customer_id_list[i]))
                # 取出订单的支付信息
                payInfoList = ToolsHandler.get_json_result(order_detail, '$..payInfoList')
                # 取出订单的菜品信息
                foodList = ToolsHandler.get_json_result(order_detail, '$..foodList')
                # 判断菜品信息和支付信息都不为空才进行后续操作
                if payInfoList is not None and foodList != [] and foodList is not None:
                    # 将支付数据调用order_pay_info_cleaning方法进行组装
                    pay_ment_list = self.order_pay_info_cleaning(payInfoList, order_no_list[i])
                    # 将菜品数据调用order_food_info_cleaning方法进行组装
                    food_list = order_food_info_cleaning(foodList, order_no_list[i])
                    # 取出订单所有数据
                    detail_data = ToolsHandler.get_json_result(order_detail, '$..data')
                    # 调用order_upload_data_cleaning方法进行最后的数据组装
                    upload_data_dict = self.order_upload_data_cleaning(detail_data, pay_ment_list, food_list)
                    # 将组装好的数据调用insert_sql_assembly方法插入数据库
                    self.insert_sql_assembly(order_no_list[i], '0', upload_data_dict)
        # 最后将数据库进行关闭
        self.sql_server.db_close()

    def get_overseas_upload_data(self) -> dict:
        """
        获取海外物业订单上传数据
        :return:
        """
        # 查询订单数据SQL
        sql = 'SELECT * FROM "overseas_upload_order";'
        # 执行查询语句
        order_data = self.sql_server.find_data(sql)
        # 判断数据长度是否大于1,大于的话说明有数据,没有则需要对数据新增数据
        if len(order_data) > 1:
            payload = order_data[0][6]  # 取出组装好地请求数据
            sql_id = str(order_data[0][0])  # 取出当前取出数据的id,后续对数据进行删除
            # 删除数据SQL
            delete_sql = 'DELETE FROM "overseas_upload_order" WHERE ("id"={})'.format(sql_id)
            # 执行删除语句
            self.sql_server.db_data_operate(delete_sql)
            # 关闭数据连接
            self.sql_server.db_close()
            result_info = {"code": 200, "message": "请求成功", "data": payload}
            return result_info
        else:
            result_info = {"code": 5009, "message": "数据正在处理中,请稍后重试~"}
            self.order_data_cleaning()
            return result_info


if __name__ == '__main__':
    test = OverseasUploadOrderPayloadServer('823882', 'sit')
    result = test.get_overseas_upload_data()
    print(result)
